<template>
  <div class="app-container">
    <div class="filter-container">
      <el-date-picker
        v-model="listQuery.tradingDayArray"
        value-format="yyyy-MM-dd"
        type="daterange"
        class="filter-item"
        range-separator="To"
        start-placeholder="Start time"
        end-placeholder="End time"
      />

      <el-select v-model="listQuery.symbolType" class="filter-item" clearable placeholder="symbol type">
        <el-option v-for="item in options.symbolType" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-select v-model="listQuery.acctId" class="filter-item" clearable placeholder="account id">
        <el-option v-for="item in options.accountId" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-select v-model="listQuery.symbol" class="filter-item" clearable placeholder="symbol">
        <el-option v-for="item in options.symbol" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>

      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">Filter</el-button>
    </div>
    <el-row :gutter="32">
      <el-col :xs="24" :sm="24" :lg="12">
        <div class="chart-container">
          <div class="filter-container">
            <el-switch v-model="dayChartType" active-text="single" inactive-text="accumulated" />
          </div>
          <line-chart :chart-data="dayChartData" :show-type="dayChartType" :title="dayChartTitle" @dayChartClick="handleDayChartClick" />
        </div>
      </el-col>
      <el-col :xs="24" :sm="24" :lg="12">
        <div class="chart-container">
          <div class="filter-container">
            <el-switch v-model="timeChartType" active-text="single" inactive-text="accumulated" />
          </div>
          <bar-chart :chart-data="timeChartData" :show-type="timeChartType" :title="timeChartTitle" @barChartRangeChange="handleBarChartRangeChange" />
        </div>
      </el-col>
      <el-col :xs="24" :sm="24" :lg="24">
        <div style="text-align: right; margin-bottom: 20px;">
          <el-button :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
            Export
          </el-button>
        </div>
        <el-table v-loading="listLoading" :data="tableData.slice((currentPage-1)*pagesize,currentPage*pagesize)" element-loading-text="正在查询中。。。" fit highlight-current-row>
          <el-table-column v-for="(item, index) in gridTableHeader" :key="index" :prop="index" :label="item" sortable show-overflow-tooltip />
        </el-table>
        <div style="text-align: right; margin-top: 20px;">
          <el-pagination
            :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="tableData.length"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { dayList, timeList, stockType } from "@/api/vadmin/stock/stock";
import LineChart from "./dashboard/LineChart";
import BarChart from "./dashboard/BarChart";

export default {
  components: { LineChart, BarChart },
  data() {
    return {
      listLoading: false,
      downloadLoading: false,

      tableData: [],
      gridTableHeader: { gridTime: "gridTime", pnlToday: "pnlToday", pnlHold: "pnlHold", pnlTrade: "pnlTrade" },

      dayChartData: { tradingDay: [], pnlToday: [], pnlHold: [], pnlTrade: [] },
      dayChartType: false,
      dayChartTitle: "",

      timeChartData: { gridTime: [], pnlToday: [], pnlHold: [], pnlTrade: [] },
      timeChartType: false,
      timeChartTitle: "",

      listQuery: {
        tradingDayArray: [],
        accountId: undefined,
        symbol: undefined,
        symbolType: undefined
      },
      query: {},
      options: { symbol: {}, accountId: {}, symbolType: {}},
      currentPage: 1,
      pagesize: 20
    };
  },
  mounted() {
    this.getTypes();
    this.getDayList();
  },
  methods: {
    getTypes() {
      stockType().then(response => {
        this.options.accountId = response.data.label;
        this.options.symbol = response.data.label2;
        this.options.symbolType = response.data.label3;
      }).catch(() => {
      });
    },

    getDayList() {
      dayList(this.query).then(response => {
        this.dayChartTitle = "";

        if (this.query.acctId) {
          this.dayChartTitle = this.query.acctId + "_";
        }
        if (this.query.symbol) {
          this.dayChartTitle += this.query.symbol + "_";
        }
        if (this.query.beginDate) {
          this.dayChartTitle += this.query.beginDate + "-" + this.query.endDate;
        }

        const chartData = { tradingDay: [], pnlToday: [], pnlHold: [], pnlTrade: [] };
        for (let i = 0, len = response.data.length; i < len; i++) {
          chartData.tradingDay.push(response.data[i].tradingDay);
          chartData.pnlToday.push(response.data[i].pnlToday);
          chartData.pnlHold.push(response.data[i].pnlHold);
          chartData.pnlTrade.push(response.data[i].pnlTrade);
        }
        this.dayChartData = chartData;
        this.timeChartData = { gridTime: [], pnlToday: [], pnlHold: [], pnlTrade: [] };
        this.getTimeList(chartData.tradingDay[response.data.length - 1]);
      }).catch(() => {
      });
    },

    getTimeList(day) {
      const timeQuery = JSON.parse(JSON.stringify(this.query));
      timeQuery.tradingDay = day;
      this.timeChartTitle = "";

      if (timeQuery.acctId) {
        this.timeChartTitle = timeQuery.acctId + "_";
      }
      if (timeQuery.symbol) {
        this.timeChartTitle += timeQuery.symbol + "_";
      }
      this.timeChartTitle += timeQuery.tradingDay;

      timeList(timeQuery).then(response => {
        const chartData = { gridTime: [], pnlToday: [], pnlHold: [], pnlTrade: [] };
        for (let i = 0, len = response.data.length; i < len; i++) {
          chartData.gridTime.push(response.data[i].gridTime);
          chartData.pnlToday.push(response.data[i].pnlToday);
          chartData.pnlHold.push(response.data[i].pnlHold);
          chartData.pnlTrade.push(response.data[i].pnlTrade);
        }
        this.timeChartData = chartData;
      }).catch(() => {
      });
    },

    handleFilter() {
      this.query = {};
      this.query = JSON.parse(JSON.stringify(this.listQuery));
      if (this.query.tradingDayArray && this.query.tradingDayArray.length === 2) {
        this.query.beginDate = this.query.tradingDayArray[0];
        this.query.endDate = this.query.tradingDayArray[1];
      } else {
        this.query.beginDate = null;
        this.query.endDate = null;
      }

      delete this.query.tradingDayArray;
      this.getDayList();
    },

    handleDayChartClick(data) {
      this.getTimeList(data.name);
    },

    handleBarChartRangeChange(data) {
      const formatData = [];
      for (let i = 0, len = data.gridTime.length; i < len; i++) {
        formatData.push({
          "gridTime": data.gridTime[i],
          "pnlToday": data.pnlToday[i],
          "pnlHold": data.pnlHold[i],
          "pnlTrade": data.pnlTrade[i]
        });
      }
      this.tableData = formatData;
      this.currentPage = 1;
    },

    handleSizeChange(size) {
      this.pagesize = size;
    },

    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
    },

    /** export table data */
    handleDownload() {
      if (this.tableData.length === 0) {
        [
          this.$notify({
            title: "error",
            message: "table is empty"
          })
        ];
        return;
      }
      this.downloadLoading = true;

      import("@/vendor/Export2Excel").then(excel => {
        const tHeader = ["gridTime", "pnlToday", "pnlHold", "pnlTrade"];
        const filterVal = ["gridTime", "pnlToday", "pnlHold", "pnlTrade"];
        const data = this.formatJson(filterVal);
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: "table-list"
        });
        this.downloadLoading = false;
      });
    },

    formatJson(filterVal) {
      return this.tableData.map(v => filterVal.map(j => {
        return v[j];
      }));
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.content-container {
  padding: 32px;
  background-color: rgb(240, 242, 245);

  .chart-wrapper {
    background: #fff;
    padding: 16px 16px 0;
    margin-bottom: 32px;
  }
}

.chart-container {
  background-color: rgb(240, 242, 245);
  padding: 16px 16px 0;
  margin-bottom: 32px;
}
</style>
